<template>
  <div :class="prefixCls" class="login-container" id="loginContainer">
    <!-- 背景装饰元素 -->
    <div class="bg-decoration">
      <div class="floating-circle circle-1"></div>
      <div class="floating-circle circle-2"></div>
      <div class="floating-circle circle-3"></div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧logo和标题 -->
      <div class="logo-section" id="logoSection">
        <div class="logo-container">
          <img alt="" class="logo-img" src="@/assets/imgs/login/dy_logo.png" />
          <h1 class="logo-title">{{ underlineToHump(appStore.getTitle) }}</h1>
        </div>
        <p class="logo-subtitle">简约、高效、现代化的管理系统</p>
      </div>

      <!-- 右侧登录表单 -->
      <div class="form-section">
        <!-- 工具栏 -->
        <div class="toolbar">
          <ThemeSwitch />
          <LocaleDropdown />
        </div>

        <!-- 登录卡片 -->
        <div class="login-card">
          <!-- 登录方式切换 -->
          <div class="login-tabs">
            <div 
              class="tab-item" 
              :class="{ active: loginType === 'password' }"
              @click="switchLoginType('password')"
            >
              <Icon icon="ep:lock" :size="18" />
              <span>密码登录</span>
            </div>
            <!-- <div 
              class="tab-item" 
              :class="{ active: loginType === 'qrcode' }"
              @click="switchLoginType('qrcode')"
            >
              <Icon icon="simple-icons:douyin" :size="18" />
              <span>抖音扫码</span>
            </div> -->
          </div>

          <!-- 登录表单区域 -->
          <div class="form-container">
            <!-- 密码登录表单 -->
            <Transition
              name="slide-fade"
              mode="out-in"
            >
              <div v-if="loginType === 'password'" key="password" class="form-content">
                <el-form
                  ref="formLogin"
                  :model="loginData.loginForm"
                  :rules="LoginRules"
                  class="login-form"
                  size="large"
                >
                  <!-- 租户名称 -->
                  <el-form-item v-if="loginData.tenantEnable === 'true'" prop="tenantName">
                    <el-input
                      v-model="loginData.loginForm.tenantName"
                      :placeholder="t('login.tenantNamePlaceholder')"
                      :prefix-icon="iconHouse"
                      class="form-input"
                    />
                  </el-form-item>

                  <!-- 用户名 -->
                  <el-form-item prop="username">
                    <el-input
                      v-model="loginData.loginForm.username"
                      :placeholder="t('login.usernamePlaceholder')"
                      :prefix-icon="iconAvatar"
                      class="form-input"
                    />
                  </el-form-item>

                  <!-- 密码 -->
                  <el-form-item prop="password">
                    <el-input
                      v-model="loginData.loginForm.password"
                      :placeholder="t('login.passwordPlaceholder')"
                      :prefix-icon="iconLock"
                      show-password
                      type="password"
                      class="form-input"
                      @keyup.enter="getCode()"
                    />
                  </el-form-item>

                  <!-- 记住我和忘记密码 -->
                  <div class="form-options">
                    <el-checkbox v-model="loginData.loginForm.rememberMe">
                      {{ t('login.remember') }}
                    </el-checkbox>
                    <!-- <el-link type="primary" class="forget-password">
                      {{ t('login.forgetPassword') }}
                    </el-link> -->
                  </div>

                  <!-- 登录按钮 -->
                  <el-button
                    :loading="loginLoading"
                    type="primary"
                    size="large"
                    class="login-btn"
                    @click="getCode()"
                  >
                    {{ t('login.login') }}
                  </el-button>
                </el-form>
              </div>

              <!-- 抖音扫码登录 -->
              <div v-else key="qrcode" class="form-content qr-content">
                <!-- 抖音扫码登录按钮 -->
                <div class="douyin-login-section" @click="openDouYinLogin()">
                  <div class="douyin-logo">
                    <img src="@/assets/imgs/login/dy_logo.png" style="width: 120px;height: 120px;" />
                  </div>
                  <div class="douyin-text">
                    点击进行抖音扫码登录
                  </div>
                </div>
              </div>
            </Transition>
          </div>
        </div>
      </div>
    </div>

    <!-- 验证码组件 -->
    <Verify
      v-if="loginData.captchaEnable === 'true'"
      ref="verify"
      :captchaType="captchaType"
      :imgSize="{ width: '400px', height: '200px' }"
      mode="pop"
      @success="handleLogin"
    />
  </div>
</template>

<script lang="ts" setup>
import { ElLoading } from 'element-plus'
import { underlineToHump } from '@/utils'
import { useDesign } from '@/hooks/web/useDesign'
import { useAppStore } from '@/store/modules/app'
import { useIcon } from '@/hooks/web/useIcon'
import { usePermissionStore } from '@/store/modules/permission'
import { required } from '@/utils/formRules'
import * as LoginApi from '@/api/login'
import * as authUtil from '@/utils/auth'
import { ThemeSwitch } from '@/layout/components/ThemeSwitch'
import { LocaleDropdown } from '@/layout/components/LocaleDropdown'
import type { RouteLocationNormalizedLoaded } from 'vue-router'
import { onMounted } from "vue";

defineOptions({ name: 'Login' })

const { t } = useI18n()
const message = useMessage()
const route = useRoute()
const { currentRoute, push } = useRouter()

const appStore = useAppStore()
const { getPrefixCls } = useDesign()
const prefixCls = getPrefixCls('login')
const iconHouse = useIcon({ icon: 'ep:house' })
const iconAvatar = useIcon({ icon: 'ep:avatar' })
const iconLock = useIcon({ icon: 'ep:lock' })
const formLogin = ref()
const permissionStore = usePermissionStore()
const loginLoading = ref(false)
const verify = ref()
const captchaType = ref('blockPuzzle')
const redirect = ref<string>('')

// 登录类型
const loginType = ref('password')

// 表单验证规则
const LoginRules = {
  tenantName: [required],
  username: [required],
  password: [required]
}

// 登录数据
const loginData = reactive({
  captchaEnable: import.meta.env.VITE_APP_CAPTCHA_ENABLE,
  tenantEnable: import.meta.env.VITE_APP_TENANT_ENABLE,
  loginForm: {
    tenantName: import.meta.env.VITE_APP_DEFAULT_LOGIN_TENANT || '',
    username: import.meta.env.VITE_APP_DEFAULT_LOGIN_USERNAME || '',
    password: import.meta.env.VITE_APP_DEFAULT_LOGIN_PASSWORD || '',
    captchaVerification: '',
    rememberMe: true
  }
})

// 切换登录方式
const switchLoginType = (type: 'password' | 'qrcode') => {
  loginType.value = type
  if (type === 'qrcode') {
    console.log('切换登录方式===', type)
  }else{
    console.log('切换登录方式===', type)
  }
}

//点击跳转抖音登录
const openDouYinLogin = (userId: string) => {
  LoginApi.getDyQrcode(userId).then(res => {
    console.log('二维码获取===', res)
    window.location.href = res
  })
}

// 获取验证码
const getCode = async () => {
  const form = unref(formLogin)
  if (!form) return
  
  try {
    const valid = await form.validate()
    if (!valid) return
    
    if (loginData.captchaEnable === 'false') {
      await handleLogin({})
    } else {
      verify.value.show()
    }
  } catch (error) {
    console.log('表单验证失败:', error)
  }
}

// 处理登录
const loading = ref() // ElLoading.service 返回的实例
const handleLogin = async (params: any) => {
  loginLoading.value = true
  try {
    // 获取租户ID
    await getTenantId()
    
    const data = {
      ...loginData.loginForm,
      captchaVerification: params.captchaVerification
    }
    
    const loginRes = await LoginApi.login(data)
    if (loginRes) {
      // 判断是否为SSO登录
      if (redirect.value.indexOf('sso') !== -1) {
        window.location.href = window.location.href.replace('/login?redirect=', '')
      } else {
        console.log('登录成功', loginRes)
        LoginApi.checkDyLogin(loginRes.userId).then(async res => {
          if (res) {
            console.log('需要扫码登录', res)
            if(res.valid){
              // 设置loading
              loading.value = ElLoading.service({
                lock: true,
                text: '正在加载系统中...',
                background: 'rgba(0, 0, 0, 0.7)'
              })
              
              // 处理记住我逻辑
              if (loginData.loginForm.rememberMe) {
                authUtil.setLoginForm(loginData.loginForm)
              } else {
                authUtil.removeLoginForm()
              }
              // 设置token
              authUtil.setToken(loginRes)
              message.success(t('login.loginSuccessTitle'))
              // message.success(redirect.value)
              if (!redirect.value) {
                redirect.value = '/index'
              }
              redirect.value = '/index'
              console.log('登录成功，准备跳转到:', redirect.value)
              await push({ path: redirect.value || permissionStore.addRouters[0].path })
              loginLoading.value = false
              if (loading.value) {
                loading.value.close()
              }
            }else{
              // 设置loading
              loading.value = ElLoading.service({
                lock: true,
                text: res.message+'，正在跳转',
                background: 'rgba(0, 0, 0, 0.7)'
              })
              // 处理记住我逻辑
              if (loginData.loginForm.rememberMe) {
                authUtil.setLoginForm(loginData.loginForm)
              } else {
                authUtil.removeLoginForm()
              }
              // 设置token
              authUtil.setToken(loginRes)
              setTimeout(() => {
                loginLoading.value = false
                if (loading.value) {
                  loading.value.close()
                }
                openDouYinLogin(loginRes.userId)
              }, 1000);
            }
          }
        })
      }
    }
  } catch (error) {
    console.error('登录失败:', error)
    message.error('登录失败，请重试')
  } finally {
    loginLoading.value = false
    if (loading.value) {
      loading.value.close()
    }
  }
}

// 获取租户ID
const getTenantId = async () => {
  if (loginData.tenantEnable === 'true') {
    const res = await LoginApi.getTenantIdByName(loginData.loginForm.tenantName)
    authUtil.setTenantId(res)
  }
}

watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string
  },
  {
    immediate: true
  }
)

onMounted(() => {
  //设置背景动效
  VANTA.WAVES({
    el: "#loginContainer",
    mouseControls: true,
    touchControls: true,
    gyroControls: false,
    minHeight: 200.00,
    minWidth: 200.00,
    scale: 1.00,
    scaleMobile: 1.00
  })
  //设置登录模块左侧动效
  VANTA.WAVES({
    el: "#logoSection",
    mouseControls: true,
    touchControls: true,
    gyroControls: false,
    minHeight: 200.00,
    minWidth: 200.00,
    scale: 1.00,
    scaleMobile: 1.00
  })
})
</script>

<style lang="scss" scoped>
$prefix-cls: #{$namespace}-login;

.#{$prefix-cls} {
  &.login-container {
    position: relative;
    width: 100vw;
    height: 100vh;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

// 背景装饰
.bg-decoration {
  display: none;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  overflow: hidden;
}

.floating-circle {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  animation: float 6s ease-in-out infinite;
  
  &.circle-1 {
    width: 120px;
    height: 120px;
    top: 10%;
    left: 10%;
    animation-delay: 0s;
  }
  
  &.circle-2 {
    width: 80px;
    height: 80px;
    top: 60%;
    right: 15%;
    animation-delay: 2s;
  }
  
  &.circle-3 {
    width: 100px;
    height: 100px;
    bottom: 20%;
    left: 20%;
    animation-delay: 4s;
  }
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px) rotate(0deg);
  }
  50% {
    transform: translateY(-20px) rotate(10deg);
  }
}

// 主要内容
.main-content {
  display: flex;
  width: 100%;
  max-width: 1200px;
  height: 100%;
  max-height: 600px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 20px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  animation: slideIn 0.8s ease-out;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(30px) scale(0.9);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

// 左侧logo区域
.logo-section {
  flex: 1;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 40px;
  color: white;
  position: relative;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="50" cy="50" r="1" fill="%23ffffff" opacity="0.1"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>') repeat;
    opacity: 0.5;
  }
}

.logo-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
  position: relative;
  z-index: 1;
}

.logo-img {
  width: 80px;
  height: 80px;
  margin-bottom: 16px;
  animation: pulse 2s ease-in-out infinite;
}

@keyframes pulse {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
}

.logo-title {
  font-size: 28px;
  font-weight: 700;
  margin: 0;
  text-align: center;
  background: linear-gradient(45deg, #fff, #e0e7ff);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.logo-subtitle {
  font-size: 16px;
  opacity: 0.9;
  text-align: center;
  margin: 0;
  position: relative;
  z-index: 1;
}

// 右侧表单区域
.form-section {
  flex: 1;
  padding: 40px;
  display: flex;
  flex-direction: column;
  position: relative;
}

.toolbar {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-bottom: 20px;
}

.login-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

// 登录方式切换
.login-tabs {
  display: flex;
  background: #f5f7fa;
  border-radius: 12px;
  padding: 4px;
  margin-bottom: 32px;
  position: relative;
}

.tab-item {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 12px 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 500;
  color: #64748b;
  position: relative;
  z-index: 2;
  
  &.active {
    background: white;
    color: var(--el-color-primary);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
  
  &:hover:not(.active) {
    color: var(--el-color-primary);
    background: rgba(255, 255, 255, 0.5);
  }
}

// 表单容器
.form-container {
  position: relative;
  min-height: 320px;
}

.form-content {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

// 过渡动画
.slide-fade-enter-active,
.slide-fade-leave-active {
  transition: all 0.4s ease;
}

.slide-fade-enter-from {
  opacity: 0;
  transform: translateX(30px);
}

.slide-fade-leave-to {
  opacity: 0;
  transform: translateX(-30px);
}

// 表单样式
.login-form {
  .form-input {
    :deep(.el-input__wrapper) {
      border-radius: 12px;
      padding: 0 16px;
      height: 48px;
      box-shadow: none;
      border: 1px solid #e2e8f0;
      transition: all 0.3s ease;
      
      &:hover {
        border-color: var(--el-color-primary);
      }
      
      &.is-focus {
        border-color: var(--el-color-primary);
        box-shadow: 0 0 0 3px rgba(var(--el-color-primary-rgb), 0.1);
      }
    }
    
    :deep(.el-input__inner) {
      height: 46px;
      line-height: 46px;
    }
  }
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 20px 0 24px;
  
  .forget-password {
    font-size: 14px;
  }
}

.login-btn {
  width: 100%;
  height: 48px;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  background: linear-gradient(135deg, var(--el-color-primary) 0%, #5a67d8 100%);
  border: none;
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 20px rgba(var(--el-color-primary-rgb), 0.3);
  }
  
  &:active {
    transform: translateY(0);
  }
}

// 二维码样式
.qr-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.qr-container {
  text-align: center;
}

.qr-wrapper {
  position: relative;
  display: inline-block;
  margin-bottom: 24px;
  padding: 20px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.qr-code {
  display: block;
}

.qr-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(5px);
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    background: rgba(255, 255, 255, 0.95);
  }
}

.refresh-icon {
  color: #64748b;
  transition: transform 0.3s ease;
  
  &:hover {
    transform: rotate(180deg);
  }
}

.success-icon {
  color: #22c55e;
  animation: checkmark 0.6s ease;
}

@keyframes checkmark {
  0% {
    transform: scale(0);
  }
  50% {
    transform: scale(1.2);
  }
  100% {
    transform: scale(1);
  }
}

.qr-tips {
  .tip-text {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    font-size: 14px;
    color: #64748b;
    margin: 0;
    
    &.expired {
      color: #ef4444;
    }
    
    &.scanning {
      color: #f59e0b;
    }
    
    &.success {
      color: #22c55e;
    }
  }
  
  .douyin-icon {
    color: #fe2c55;
  }
  
  .loading-icon {
    animation: spin 1s linear infinite;
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

// 响应式设计
@media (max-width: 768px) {
  .main-content {
    flex-direction: column;
    max-width: 400px;
    max-height: none;
    margin: 20px;
  }
  
  .logo-section {
    flex: none;
    padding: 30px 20px;
  }
  
  .form-section {
    padding: 30px 20px;
  }
  
  .logo-img {
    width: 60px;
    height: 60px;
  }
  
  .logo-title {
    font-size: 24px;
  }
  
  .logo-subtitle {
    font-size: 14px;
  }
}
.douyin-login-section{
  width: 100%;
  cursor: pointer;
}
.douyin-logo{
  width: 100%;
  display: flex;
  justify-content: center;
}
.douyin-text{
  margin-top: 10px;
  width: 100%;
  font-size: 14px;
  color: #666;
  text-align: center;
}
</style>